package com.soap.desensitize.strategy.irreversible;

import com.soap.desensitize.encry.irreversible.AbstractIRreversibleEncry;
import com.soap.desensitize.exception.strategy.EncodeException;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * @desc	sha512加密
 * @author 	HJH
 * @time	2022-04-21
 */
public class Sha512Strategy extends AbstractIRreversibleEncry<String> {
    private static Sha512Strategy instance = null;
    private Sha512Strategy(){}

    /**
     * @desc 获得实例
     * @return
     */
    public static synchronized Sha512Strategy getInstance(){
        if(instance == null){
            instance = new Sha512Strategy();
        }
        return instance;
    }

    /**
     *
     * @param data 待加密字符串
     * @return
     * @throws NoSuchAlgorithmException
     */
    @Override
    public String encode(String data) throws EncodeException {
        try {
            //信息摘要器                                算法名称
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            //把字符串转为字节数组
            byte[] messageDigest = md.digest(data.getBytes());
            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }
        catch (NoSuchAlgorithmException e) {
            throw new EncodeException("加密错误，加密算法不存在");
        }
    }
}
